const express = require('express');
const bodyParser = require('body-parser');

const read = require('node-readability');
const url = 'http://www.manning.com/cantelon2/';
read(url, (err, result) => {
    Article.create(
        { title: result.title, content: result.content },
        (err, article) => {
            // 将文章保存到数据库中 
        }
    );
});

const app = express();
const Article = require('./db').Article;
app.set('port', process.env.PORT || 3000);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(
    '/css/bootstrap.css', express.static('node_modules/bootstrap/dist/css/bootstrap.css')
);

app.get('/articles', (req, res, next) => {
    Article.all((err, articles) => {
        if (err) return next(err);
        // res.send(articles);
        res.format({
            json: () => {
                res.send(articles);
            },
            html: () => {
                res.render('articles.ejs', { articles: articles });
            }
        });
    });
});
app.post('/articles', (req, res, next) => {
    const url = req.body.url;

    read(url, (err, result) => {
        if (err || !result) res.status(500).send('Error downloading artiele');
        Article.create(
            { title: result.title, content: result.content },
            (err, article) => {
                //文章保存成功后, 发送状 态码为 200 的响应
                if (err) return next(err);
                res.send('OK');
            }
        );
    });
});
app.get('/articles/:id', (req, res, next) => {
    const id = req.params.id;
    Article.find(id, (err, article) => {
        if (err) return next(err);
        res.send(article);
    });
});
app.delete('/articles/:id', (req, res, next) => {
    const id = req.params.id;
    Article.delete(id, (err) => {
        if (err) return next(err);
        res.send({ message: 'Deleted' });
    });

});
app.listen(app.get('port'), () => {
    console.log('App started on port', app.get('port'));
});
module.exports = app;